<template>
  <div class="search_container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>借阅管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="always">
      <el-button type="text" @click="openWin">
        + 新增
      </el-button>

      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="读者名称">
          <el-input v-model="formInline.readerId" placeholder="读者名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="myDatas"
          border
          style="width: 100%">
        <el-table-column
            prop="borrowingRecordId"
            label="借阅记录标识"
            v-if="false"
        >
        </el-table-column>
        <el-table-column
            prop="bookId"
            label="图书"
            v-if="false">
        </el-table-column>
        <el-table-column
            prop="bookName"
            label="图书">
        </el-table-column>
        <el-table-column
            prop="readerId"
            label="读者"
            v-if="false">
        </el-table-column>
        <el-table-column
            prop="readerName"
            label="读者">
        </el-table-column>
        <el-table-column
            prop="borrowingDate"
            label="借阅日期"
        >
        </el-table-column>
        <el-table-column
            prop="userId"
            label="借阅管理员"
            v-if="false">
        </el-table-column>
        <el-table-column
            prop="userName"
            label="借阅管理员">
        </el-table-column>
        <el-table-column
            prop="borrowingStatus"
            label="借阅状态"
            :formatter="formatStatus"
        >
        </el-table-column>
        <el-table-column
            prop="renewCount"
            label="续借次数"
        >
        </el-table-column>
        <el-table-column
            prop="actualReturnDate"
            label="应归还日期"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div style="display: flex;">
            <el-button
                size="mini"
                @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <div style="margin-top: 20px; text-align: left;">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
          ></el-pagination>
        </div>
      </div>
      <el-dialog
          title="增加借阅记录"
          :visible.sync="dialogVisible"
          width="50%">
        <!--        员工表单信息-->
        <el-form ref="form" :inline="true" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="读者" prop="readerId">
            <el-select v-model="form.readerId" placeholder="请输入读者">
              <el-option
                  v-for="reader in readerOptions"
                  :key="reader.readerId"
                  :label="reader.readerName"
                  :value="reader.readerId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图书" prop="bookId">
            <el-select v-model="form.bookId" placeholder="请输入图书">
              <el-option
                  v-for="book in bookOptions"
                  :key="book.bookId"
                  :label="book.bookName"
                  :value="book.bookId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="借阅日期" prop="borrowingDate">
            <el-col :span="15">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.borrowingDate" style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="借阅状态" prop="borrowingStatus">
            <el-select v-model="form.borrowingStatus" placeholder="请选择借阅状态">
              <el-option label="借出中" value="1000"></el-option>
              <el-option label="已逾期" value="1001"></el-option>
              <el-option label="已归还" value="1002"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="续借次数" prop="renewCount">
            <el-input  placeholder="请输入续借次数" v-model="form.renewCount"></el-input>
          </el-form-item>
          <el-form-item label="借阅管理员" prop="userId">
            <el-select v-model="form.userId" placeholder="请输入借阅管理员">
              <el-option
                  v-for="user in userOptions"
                  :key="user.userId"
                  :label="user.name"
                  :value="user.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应归还日期" prop="actualReturnDate">
            <el-col :span="15">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.actualReturnDate" style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </span>
      </el-dialog>
      <el-dialog
          title="编辑借阅记录"
          :visible.sync="userVisible"
          width="50%">
        <!--        员工表单信息-->
        <el-form ref="form" :inline="true" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="借阅记录标识" prop="borrowingRecordId" v-if="false">
            <el-input placeholder="请输入借阅记录标识" v-model="form.borrowingRecordId"></el-input>
          </el-form-item>
          <el-form-item label="读者" prop="readerId">
            <el-select v-model="form.readerId" placeholder="请输入读者">
              <el-option
                  v-for="reader in readerOptions"
                  :key="reader.readerId"
                  :label="reader.readerName"
                  :value="reader.readerId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图书" prop="bookId">
            <el-select v-model="form.bookId" placeholder="请输入图书">
              <el-option
                  v-for="book in bookOptions"
                  :key="book.bookId"
                  :label="book.bookName"
                  :value="book.bookId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="借阅日期" prop="borrowingDate">
            <el-col :span="15">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.borrowingDate" style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="借阅状态" prop="borrowingStatus">
            <el-select v-model="form.borrowingStatus" placeholder="请选择借阅状态">
              <el-option label="借出中" value="1000"></el-option>
              <el-option label="已逾期" value="1001"></el-option>
              <el-option label="已归还" value="1002"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="续借次数" prop="renewCount">
            <el-input  placeholder="请输入续借次数" v-model="form.renewCount"></el-input>
          </el-form-item>
          <el-form-item label="借阅管理员" prop="userId">
            <el-select v-model="form.userId" placeholder="请输入借阅管理员">
              <el-option
                  v-for="user in userOptions"
                  :key="user.userId"
                  :label="user.name"
                  :value="user.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应归还日期" prop="actualReturnDate">
            <el-col :span="15">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.actualReturnDate" style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="userVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import {addBorrow, delBorrow, getBorrowPageData} from '../../api/borrow/borrow';
import {getReaderListData} from '../../api/reader/reader';
import {getBookListData} from '../../api/book/book';
import moment from 'moment';
import {getDepartmentListData} from "@/api/department/department";
import {getUserListData} from "@/api/user/user";
import Vue from "vue";
export default {
  data() {
    return {
      dialogVisible: false,
      userVisible: false,
      formInline: {
        readerId: '',
        page:null,
        limit:null
      },
      form:{
        bookId: "",
        readerId: "",
        borrowingDate: "",
        borrowingStatus: "",
        renewCount: "",
        userId: "",
        actualReturnDate: "",
      },
      rules: {
        bookId:[ { required: true, message: '请输入图书', trigger: 'blur' },],
        readerId:[ { required: true, message: '请输入读者', trigger: 'blur' },],
        borrowingDate:[ { required: true, message: '请输入借阅日期', trigger: 'blur' },],
        borrowingStatus:[ { required: true, message: '请输入借阅状态', trigger: 'blur' },],
        renewCount:[ { required: true, message: '请输入续借次数', trigger: 'blur' },],
        userId:[ { required: true, message: '请输入借阅管理者', trigger: 'blur' },],
        actualReturnDate:[ { required: true, message: '请输入实际归还日期', trigger: 'blur' },]
      },
      myDatas: [],
      currentPage: 1, // 当前页
      total: 0, // 数据总条数
      pageSize: 10, // 每页条数
      loading: true,
      readerOptions: [], // 存储部门选项的数组
      bookOptions: [],
      userOptions: [] // 存储部门选项的数组
    };
  },mounted() {
    this.getBorrowsPage(this.formInline);
  },
  methods: {
    openWin(){
      this.dialogVisible = true;
      this.form.borrowingRecordId = '';
      this.form.bookId = '';
      this.form.readerId =  '';
      this.form.borrowingDate =  '';
      this.form.borrowingStatus = '';
      this.form.renewCount =  '';
      this.form.userId =  '';
      this.form.actualReturnDate = '';
      if (this.$refs.addForm) {
        this.$refs.addForm.reset();
      }
    },
    //页面初始化，调用接口，入参是page=1&size=10
    getBorrowsPage(params){
      getBorrowPageData(params).then((response)=>{
        this.myDatas =response.content;
        this.total = response.content.length;
      });
    },
    //点击查询按钮，掉用接口
    onSearch(){
      const formData = this.formInline;
      getBorrowPageData(formData).then((response)=>{
        this.myDatas =response.content;
        this.total = response.content.length;
      });
    },
    // 点击分页里的按钮，显示分页数据
    getAccountListByPage() {
      // 收集当前页码 和 每页显示条数
      const formData = this.formInline;
      formData.page = this.currentPage
      formData.size = this.pageSize
      // 发送ajax请求 把分页数据发送给后端
      getBorrowPageData(formData).then(response => {
        console.log("对应页码的数据:", response);
        // 赋值给对应的变量即可
        this.total = response.total;
        this.myDatas = response.content;
        // 如果当前页没有数据 且 排除第一页
        if (!response.content.length && this.currentPage !== 1) {
          // 页码减去 1
          this.currentPage -= 1;
          // 再调用自己
          this.getAccountListByPage();
        }
      })
          .catch(err => {
            console.log(err);
          });
    },
    // 每页显示条数改变 就会触发这个函数
    handleSizeChange(val) {
      // 保存每页显示的条数
      this.pageSize = val;
      // 调用分页函数
      this.getAccountListByPage();
    },
    // 当前页码改变 就会触发这个函数
    handleCurrentChange(val) {
      // 保存当前页码
      this.currentPage = val;
      // 调用分页函数
      this.getAccountListByPage();
    },
    //点击新增按钮，进行数据提交
    handleSubmit(){
      console.log(this.form.borrowingRecordId);
      this.$refs.form.validate(valid => {
        if (valid) {
          // 构造要提交的数据对象
          const data = {
            borrowingRecordId:this.form.borrowingRecordId,
            bookId: this.form.bookId,
            readerId: this.form.readerId,
            borrowingDate: moment(this.form.borrowingDate ).format('YYYY-MM-DD HH:mm:ss'),
            borrowingStatus: this.form.borrowingStatus,
            renewCount: this.form.renewCount,
            userId: this.form.userId,
            actualReturnDate:  moment(this.form.actualReturnDate ).format('YYYY-MM-DD HH:mm:ss'),
          };
          addBorrow(data).then((response)=>{
            this.$message({
              type: 'success',
              message: '新增数据成功'
            });
            // 刷新页面
            window.location.reload();
          })

        }
      })
    },
    //点击数据每行的删除按钮
    handleDelete(item){
      console.log(item);
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delBorrow({ id: item.borrowingRecordId }).then((response) => {
          const index = this.myDatas.indexOf(item);
          this.myDatas.splice(index, 1);
        })
        this.$message({
          type: 'success',
          message: '删除数据成功'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //点击编辑按钮，进行修改数据
    handleEdit(item){
      this.userVisible = true;
      this.form.borrowingRecordId = item.borrowingRecordId;
      this.form.bookId = item.bookId;
      this.form.readerId = item.readerId;
      this.form.borrowingDate = item.borrowingDate;
      this.form.borrowingStatus = item.borrowingStatus;
      this.form.renewCount = item.renewCount;
      this.form.userId = item.userId;
      this.form.actualReturnDate = item.actualReturnDate;
    },
    async getReaders() {
      try {
        const response = await getReaderListData();
        this.readerOptions = response; // 假设后台接口返回的数据结构为[{ id: 1, name: '技术部' }, { id: 2, name: '人事部' }, ...]
      } catch (error) {
        console.error('Failed to get reader:', error);
      }
    },
    async getBooks() {
      try {
        const response = await getBookListData();
        this.bookOptions = response; // 假设后台接口返回的数据结构为[{ id: 1, name: '技术部' }, { id: 2, name: '人事部' }, ...]
      } catch (error) {
        console.error('Failed to get book:', error);
      }
    },
    async getUsers() {
      try {
        const response = await getUserListData();
        this.userOptions = response; // 假设后台接口返回的数据结构为[{ id: 1, name: '技术部' }, { id: 2, name: '人事部' }, ...]
      } catch (error) {
        console.error('Failed to get user:', error);
      }
    },
    formatStatus(row) {
      return this.$options.filters.borrowingStatus(row.borrowingStatus);
    },

  },computed:{

  },
  created() {
    this.getReaders(); // 在组件创建时获取部门数据
    this.getBooks();
    this.getUsers();
  },
};
Vue.filter('borrowingStatus', function(value) {
  const chineseMap = {
    1000: '借出中',
    1001: '已逾期',
    1002: '已归还'
  };
  return chineseMap[value] || '未知';
});

</script>